import md5 from 'js-md5'
import * as cache from '../../util/cache'
import expired from '../../config/expired'

const tokeKey = 'spsp' + md5('token')
const infoKey = 'sfsf' + md5('info')

export default {
  namespaced: true,
  state: {
    token: null,
    info: null
  },
  getters: {
    token: state => {
      if (state.token === null) {
        state.token = cache.get(tokeKey)
      }
      return state.token
    },
    info: state => {
      if (state.info === null) {
        state.info = cache.get(infoKey)
      }
      return state.info
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      cache.save(tokeKey, token, expired.userToken)
    },
    SET_INFO: (state, info) => {
      state.info = info
      cache.save(infoKey, info, expired.referrer)
    },
    SET_LOGOUT: (state) => {
      state.token = null
      state.info = null
      cache.remove(tokeKey)
      cache.remove(infoKey)
    },
  },
  actions: {
    login: ({ commit }, token) => {
      commit('SET_TOKEN', token)
    },
    set_info: ({ commit }, info) => {
      commit('SET_INFO', info)
    },
    logout: ({ commit }) => {
      commit('SET_LOGOUT')
    },
  }
}
